package com.collection.common.base;

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 检测管理员是否登录的过滤器
 * @author 冯勇
 *
 */
public class CheckLoginFilter implements Filter {

	private HashSet<String> ignoreURI;
	private String appPath = "";

	@Override
	public void destroy() {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;

		HttpSession session = httpRequest.getSession();

		if (session.getAttribute("admin") == null) {
			String uri = httpRequest.getRequestURI();
			if (!uri.endsWith(".do") && !uri.endsWith(".jsp") && !uri.endsWith("/")) {
				chain.doFilter(request, response);
				return;
			} else {
				if (!ignoreURI.contains(uri)) {
					httpResponse.sendRedirect(appPath+"/admin/login.jsp");
					return;
				}
			}
		} 
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		appPath = filterConfig.getServletContext().getContextPath();
		ignoreURI = new HashSet<String>();
		ignoreURI.add(appPath+"/admin/login.jsp");
		ignoreURI.add(appPath+"/admin/login.do");
		ignoreURI.add(appPath+"/admin/logout.do");
		ignoreURI.add(appPath+"/admin/download/ajaxUploadDocmuentFile.do");
	}
}
